import _ from 'lodash'
import React from 'react'
import { BaseDetailPage, UdDetail, http, IBaseDetailPageState, IBaseDetailPageProps, uaaApp } from '../../../lib'
import { Button, Input, Select, Row, Col, message, Modal } from 'antd'
import ButtonGroup from 'antd/lib/button/button-group'
import Dialog from '../component/DealWith/Dialog'
import "./dealWidthDeal.scss";
import apis from '@/apis/Suggestions'
import dayjs from 'dayjs'

const {Option}=Select
const {TextArea}=Input
const { confirm } = Modal

const DealwithBtnAuth = 'customer_dealer_complaint_manager_handle'

class DealWithDeal extends BaseDetailPage<IDealWithDealProps, IDealWithDealState> {

  constructor(props) {
    super(props)
    this.state = {
      title: '投诉建议处理',
      textValue:'',
      visible:false,
      reqier:false,
      SelectDate:[],
      queryAction: () => {
        return http.get(apis.DealWithDetail, {
          params: {
            id: this.props.match.params.id
          }
        })
      },
      visibleImgUrl: '',
    }
  }

  componentDidMount(){
    super.componentDidMount()
    this.getDetailSelect()
  }

  render() {
    return super.render({
      body: (
        <div className="deal-width-deal-detail">
          <UdDetail title="查看详情" dataSource={this.state.dataSource} items={[
            { title: '客户编码', dataIndex: 'agentCode',col: { span: 8 } },
            { title: '客户名称', dataIndex: 'agentName',col: { span: 8 } },
            { title: '联系人', dataIndex: 'createdBy',col: { span: 8 } },
            { title: '联系电话', dataIndex: 'number',col: { span: 8 } },
            { title: '反馈标题', dataIndex: 'feedbackTitle' ,col: { span: 8 }},
            { title: '反馈时间', dataIndex: 'createdTime' ,col: { span: 8 }},
            { title: '问题图片', dataIndex: 'pic' ,col: { span: 8 },
              render:(Pic)=>{
                const urls = Pic.split(',')
                return(
                  <div >
                    {urls.map(url => (<img src={url} alt="" className="picSize" onClick={this.handelOpenpic}/>))}
                    <Modal
                        className="madelWeaper"
                        visible={this.state.visible}
                        footer={null}
                        onCancel={this.handleCancel}
                      >
                      <img src={this.state.visibleImgUrl} alt="问题图片" className="picModel" />
                    </Modal>
                 </div>
                )
             }
            },
            { title:'投诉建议类型', dataIndex: 'complaintTypeId', col: { span: 24 },
              nullText: <SuggestionTypeSelect options={this.state.SelectDate} suggestionTypeChange={this.suggestionTypeChange} />,
              render:(value)=>{
                return <SuggestionTypeSelect value={value} options={this.state.SelectDate} suggestionTypeChange={this.suggestionTypeChange} />
              }
            },
            { title: '往期内容', dataIndex: 'messages',col: { span: 24 },
              render:(value)=>{return<Dialog value={value} />}
            },

          ]} />

          <div>
          {uaaApp.canUse(DealwithBtnAuth) && <Row className='reply-row'>
            <TextArea className='reply-input' value={this.state.textValue} onChange={(e)=>this.setState({textValue:e.target.value})} />
            <Button type='primary' onClick={this.handelreply}>确认回复</Button>
          </Row>}
          </div>
        </div>
      ),
      footer: (
        <ButtonGroup>
          <Button type="primary" onClick={() => this.onResolvedHandle(true)}>已解决</Button>
          <Button onClick={() => this.props.history.goBack()}>返回</Button>
        </ButtonGroup>
      )
    })
  
  }
  protected handelreply =()=>{ //确认回复按钮
    console.log(this.state.dataSource)
    const { dataSource } = this.state
    if(!dataSource.complaintTypeId){
        this.setState({reqier:true})
        message.error('请选择投诉建议类型')
        return
    }
    if(!this.state.textValue){
      message.error('请填写回复内容')
      return
    }
   
    const value ={
      "content": this.state.textValue,
      "id": Number(this.props.match.params.id),
      "type": dataSource.complaintTypeId
    }
    http.post(apis.DealWithReplyMessage,value)
    .then((res)=>{
      const messages = dataSource.messages.slice()
      const nowTime = dayjs(new Date).format('YYYY-MM-DD HH:mm:ss')
      const sendName = JSON.parse(sessionStorage.getItem('UaaSysInfo'))?.profile?.realname
      // type:2员工，status:0未读
      const msg = {id:+new Date(),createdTime:nowTime,message:this.state.textValue,type:2,status:0,sendName}
      messages.push(msg)
      this.setState({
        dataSource: {...dataSource,messages},
        textValue: undefined,
      })
      message.success('回复成功')
    })
  }

  public suggestionTypeChange = (val) => {
    const { dataSource } = this.state
    const complaintTypeId = val
    this.setState({
      dataSource: {...dataSource,complaintTypeId}
    })
  }


  private handelOpenpic = (e) =>{ //打开图片模态框
    const visibleImgUrl = e.target.src
    this.setState({
      visible: true,
      visibleImgUrl,
    });
   }
   private handleCancel = () => { //关闭图片模态框
    this.setState({
      visible: false,
    });
  }

  private getDetailSelect = () =>{ //回去select接口数据
    http.get(apis.DealWithType).then(res=>{
      const SelectDate = res.data.map(({id:value,type:title,id})=>({value,title,id}))
      // const SelectDate = [{value:1,title:'分类1',id:1},{value:2,title:'分类2',id:2},]
      this.setState({SelectDate})
     })
  }

  public onResolvedHandle = (type) => {
    confirm({
      title: '确定要关闭该问题吗？',
      onOk: () => {
        const id = this.props.match.params.id
        return http.post(apis.SuggestionsIsHaveDone + "?id=" + id + "&status=2").then(res => {
          message.success('处理成功')
          this.props.history.goBack()
        })
      }
    })
  }

}

interface IDealWithDealProps extends IBaseDetailPageProps<{
  id: string
}> {
  
}

interface IDealWithDealState extends IBaseDetailPageState {
  textValue:any
  reqier:boolean
  visible:boolean
  SelectDate:any
  visibleImgUrl: string
}

export default DealWithDeal

function SuggestionTypeSelect (props) {
  const { options=[], value, suggestionTypeChange, onChange } = props
  const selectChange = (val) => {
    onChange&&onChange(val)
    suggestionTypeChange&&suggestionTypeChange(val)
  }
  return (
    <Select placeholder='请选择投诉建议类型' style={{width: 200}} value={value} onChange={selectChange}>
      {options.map(({value,title,id})=>(
        <Option value={value} key={id}>{title}</Option>
      ))}
    </Select>
  )
}
